﻿/***** COLORBOX SECTION - the commands below opens interactive GUI boxes upon user selection *******************/
$(document).ready(function(){
        // Team history CB (ColorBox)
				$("#last_week").colorbox({width:"60%", inline:true, maxHeight : "95%", href:"#lastWeekPage"});
				// Personal profile CB
				$("#personal_profile").colorbox({width:"60%", inline:true, maxHeight : "95%", href:"#Personal_Profile_Wraper"});
				// HELP window CB
				$("#show_help").colorbox({width:"85%",  maxHeight : "85%", inline:true, href:"#helpPage" });
				// Talkback CB's
				$("#cell03").colorbox({width:"60%", inline:true, maxHeight : "75%", href:"#TB0"});
				$("#cell13").colorbox({width:"60%", inline:true, maxHeight : "75%", href:"#TB1"});
				$("#cell23").colorbox({width:"60%", inline:true, maxHeight : "75%", href:"#TB2"});
				$("#cell33").colorbox({width:"60%", inline:true, maxHeight : "75%", href:"#TB3"});
				$("#cell43").colorbox({width:"60%", inline:true, maxHeight : "75%", href:"#TB4"});
				$("#cell53").colorbox({width:"60%", inline:true, maxHeight : "75%", href:"#TB5"});
				$("#cell63").colorbox({width:"60%", inline:true, maxHeight : "75%", href:"#TB6"});
				$("#cell73").colorbox({width:"60%", inline:true, maxHeight : "75%", href:"#TB7"});
				$("#cell83").colorbox({width:"60%", inline:true, maxHeight : "75%", href:"#TB8"});
				$("#cell93").colorbox({width:"60%", inline:true, maxHeight : "75%", href:"#TB9"});
				$("#cell103").colorbox({width:"60%", inline:true, maxHeight : "75%", href:"#TB10"});
				$("#cell113").colorbox({width:"60%", inline:true, maxHeight : "75%", href:"#TB11"});
				$("#cell123").colorbox({width:"60%", inline:true, maxHeight : "75%", href:"#TB12"});
				$("#cell133").colorbox({width:"60%", inline:true, maxHeight : "75%", href:"#TB13"});
				$("#cell143").colorbox({width:"60%", inline:true, maxHeight : "75%", href:"#TB14"});
				$("#cell153").colorbox({width:"60%", inline:true, maxHeight : "75%", href:"#TB15"});
				// "Traffic light"(Agreement\Disagreement) CB's
				$("#cell06").colorbox({width:"400px", inline:true, scrolling:true, maxHeight : "60%", href:"#display_agreement_div0"});
				$("#cell16").colorbox({width:"400px", inline:true, scrolling:true, maxHeight : "60%", href:"#display_agreement_div1"});
				$("#cell26").colorbox({width:"400px", inline:true, scrolling:true, maxHeight : "60%", href:"#display_agreement_div2"});
				$("#cell36").colorbox({width:"400px", inline:true, scrolling:true, maxHeight : "60%", href:"#display_agreement_div3"});
				$("#cell46").colorbox({width:"400px", inline:true, scrolling:true, maxHeight : "60%", href:"#display_agreement_div4"});
				$("#cell56").colorbox({width:"400px", inline:true, scrolling:true, maxHeight : "60%", href:"#display_agreement_div5"});
				$("#cell66").colorbox({width:"400px", inline:true, scrolling:true, maxHeight : "60%", href:"#display_agreement_div6"});
				$("#cell76").colorbox({width:"400px", inline:true, scrolling:true, maxHeight : "60%", href:"#display_agreement_div7"});
				$("#cell86").colorbox({width:"400px", inline:true, scrolling:true, maxHeight : "60%", href:"#display_agreement_div8"});
				$("#cell96").colorbox({width:"400px", inline:true, scrolling:true, maxHeight : "60%", href:"#display_agreement_div9"});
				$("#cell106").colorbox({width:"400px", inline:true, scrolling:true, maxHeight : "60%", href:"#display_agreement_div10"});
				$("#cell116").colorbox({width:"400px", inline:true, scrolling:true, maxHeight : "60%", href:"#display_agreement_div11"});
				$("#cell126").colorbox({width:"400px", inline:true, scrolling:true, maxHeight : "60%", href:"#display_agreement_div12"});
				$("#cell136").colorbox({width:"400px", inline:true, scrolling:true, maxHeight : "60%", href:"#display_agreement_div13"});
				$("#cell146").colorbox({width:"400px", inline:true, scrolling:true, maxHeight : "60%", href:"#display_agreement_div14"});
				$("#cell156").colorbox({width:"400px", inline:true, scrolling:true, maxHeight : "60%", href:"#display_agreement_div15"});
				// Switch from\to Talkbacks from\to "Traffic light" CB
				$("#Agreement2TB0").colorbox({width:"60%", inline:true, maxHeight : "75%", href:"#TB0"});
				$("#TB2Agreement0").colorbox({width:"400px", inline:true, scrolling:true, maxHeight : "60%", href:"#display_agreement_div0"});
				$("#Agreement2TB1").colorbox({width:"60%", inline:true, maxHeight : "75%", href:"#TB1"});
				$("#TB2Agreement1").colorbox({width:"400px", inline:true, scrolling:true, maxHeight : "60%", href:"#display_agreement_div1"});
				$("#Agreement2TB2").colorbox({width:"60%", inline:true, maxHeight : "75%", href:"#TB2"});
				$("#TB2Agreement2").colorbox({width:"400px", inline:true, scrolling:true, maxHeight : "60%", href:"#display_agreement_div2"});
				$("#Agreement2TB3").colorbox({width:"60%", inline:true, maxHeight : "75%", href:"#TB3"});
				$("#TB2Agreement3").colorbox({width:"400px", inline:true, scrolling:true, maxHeight : "60%", href:"#display_agreement_div3"});
				$("#Agreement2TB4").colorbox({width:"60%", inline:true, maxHeight : "75%", href:"#TB4"});
				$("#TB2Agreement4").colorbox({width:"400px", inline:true, scrolling:true, maxHeight : "60%", href:"#display_agreement_div4"});
				$("#Agreement2TB5").colorbox({width:"60%", inline:true, maxHeight : "75%", href:"#TB5"});
				$("#TB2Agreement5").colorbox({width:"400px", inline:true, scrolling:true, maxHeight : "60%", href:"#display_agreement_div5"});
				$("#Agreement2TB6").colorbox({width:"60%", inline:true, maxHeight : "75%", href:"#TB6"});
				$("#TB2Agreement6").colorbox({width:"400px", inline:true, scrolling:true, maxHeight : "60%", href:"#display_agreement_div6"});
				$("#Agreement2TB7").colorbox({width:"60%", inline:true, maxHeight : "75%", href:"#TB7"});
				$("#TB2Agreement7").colorbox({width:"400px", inline:true, scrolling:true, maxHeight : "60%", href:"#display_agreement_div7"});
				$("#Agreement2TB8").colorbox({width:"60%", inline:true, maxHeight : "75%", href:"#TB8"});
				$("#TB2Agreement8").colorbox({width:"400px", inline:true, scrolling:true, maxHeight : "60%", href:"#display_agreement_div8"});
				$("#Agreement2TB9").colorbox({width:"60%", inline:true, maxHeight : "75%", href:"#TB9"});
				$("#TB2Agreement9").colorbox({width:"400px", inline:true, scrolling:true, maxHeight : "60%", href:"#display_agreement_div9"});
				$("#Agreement2TB10").colorbox({width:"60%", inline:true, maxHeight : "75%", href:"#TB10"});
				$("#TB2Agreement10").colorbox({width:"400px", inline:true, scrolling:true, maxHeight : "60%", href:"#display_agreement_div10"});
				$("#Agreement2TB11").colorbox({width:"60%", inline:true, maxHeight : "75%", href:"#TB11"});
				$("#TB2Agreement11").colorbox({width:"400px", inline:true, scrolling:true, maxHeight : "60%", href:"#display_agreement_div11"});
				$("#Agreement2TB12").colorbox({width:"60%", inline:true, maxHeight : "75%", href:"#TB12"});
				$("#TB2Agreement12").colorbox({width:"400px", inline:true, scrolling:true, maxHeight : "60%", href:"#display_agreement_div12"});
				$("#Agreement2TB13").colorbox({width:"60%", inline:true, maxHeight : "75%", href:"#TB13"});
				$("#TB2Agreement13").colorbox({width:"400px", inline:true, scrolling:true, maxHeight : "60%", href:"#display_agreement_div13"});
				$("#Agreement2TB14").colorbox({width:"60%", inline:true, maxHeight : "75%", href:"#TB14"});
				$("#TB2Agreement14").colorbox({width:"400px", inline:true, scrolling:true, maxHeight : "60%", href:"#display_agreement_div14"});
				$("#Agreement2TB15").colorbox({width:"60%", inline:true, maxHeight : "75%", href:"#TB15"});
				$("#TB2Agreement15").colorbox({width:"400px", inline:true, scrolling:true, maxHeight : "60%", href:"#display_agreement_div15"});
				//Tips&Statistics CB
				$(".stat").colorbox({width:"95%", maxHeight : "95%", inline:true, href:"#stat_tip_div", onOpen: function () { loadStat(this); } });
				//"Ask the Crowd" (Real Time Pie Charts) CB
        $(".chart_button").colorbox({opacity:0.5, width:"430px", height:"300px", maxHeight : "95%", inline:true, href:"#real_time_stat_div", onOpen: function () { drawChart(this); }, onClosed: function () { clearChart(); }} );
        
        $(window).resize(function(){    //This Jquery command updates the colorbox size with any wave window resize
            $.fn.colorbox.load();
        });
        				
				});
			
var select_box_updated=0;    //This variable indicates if the past forms drop down box in the team history page was already updated
	
/*********	TEAM HISTORY PART	****************************/
/* Gets last week's games*/
function LastWeekGamesStrState(){
	if ( wave.getState() ){
		var LastWeekGamesStr = wave.getState().get( "lw_GamesStr" );
		return LastWeekGamesStr ? LastWeekGamesStr : "";
	}
	else{
		return "";
	}
}
/*Updates last week game table with relevant matches*/
function RefreshLastWeekGames(LastWeekGamesStr){
	if(LastWeekGamesStr && LastWeekGamesStr!=""){
		var FieldsArray = LastWeekGamesStr.split("#");
		FieldsArray = reverseArray(FieldsArray,3);
		for(j=3;j<6;j++){
			tempFieldArray = FieldsArray[j-3].split("$");
			for (i=0;i<16;i++){
				document.getElementById( "lw_cell" + i + j ).innerHTML = tempFieldArray[15-i];
			}
		}
	}
}

/* Put the cost,number of correct guesses & winnings in the last week div table*/	
function RefreshLastWeekStatistics(LastWeekCost,LastWeekMoney,LastWeekCorrectGuesses){
	//new change Livnat- March 28
	if(LastWeekCost && LastWeekCost!=""){
		document.getElementById( "form_cost" ).innerHTML = parseFloat(LastWeekCost).toFixed(2);
	}

	if(LastWeekMoney && LastWeekMoney!=""){
		document.getElementById( "win_money" ).innerHTML = LastWeekMoney;    
	}

	if(LastWeekCorrectGuesses && LastWeekCorrectGuesses!=""){
		document.getElementById( "win_results" ).innerHTML = LastWeekCorrectGuesses;    
	} 

}
/* Put the Idiot in the last week div table (Name and picture)*/
function RefreshLastWeekIdiot(LastWeekIdiotID,LastWeekHotID){

	if(LastWeekIdiotID!="" && parseInt(LastWeekIdiotID)!=(-1)){
		var LastWeekIdiot=wave.getParticipantById(LastWeekIdiotID); //get idiot wave participant obj
		if (LastWeekIdiot && LastWeekIdiot!=""){
			document.getElementById( "lw_idiot_img" ).innerHTML ="<img src="+LastWeekIdiot.getThumbnailUrl()+" style='height:42px;width:42px'>";      
			document.getElementById( "lw_idiot_name" ).innerHTML = LastWeekIdiot.getDisplayName();
		}
	}
	
	if(LastWeekHotID!="" && parseInt(LastWeekHotID)!=(-1)){
		var LastWeekHot=wave.getParticipantById(LastWeekHotID); //get idiot wave participant obj
		if (LastWeekHot && LastWeekHot!=""){
			document.getElementById( "lw_king_img" ).innerHTML ="<img src="+LastWeekHot.getThumbnailUrl()+" style='height:42px;width:42px'>";      
			document.getElementById( "lw_king_name" ).innerHTML = LastWeekHot.getDisplayName();
		}
	}	
}

/*Colors the 1 X 2 cells according to the last week's results*/
function RefreshLastWeekCells(LastWeekCorrectResults){
	var cell;
	for (i=0;i<16;i++){
		for(j=0;j<3;j++){
			cell="lw_cell"+i+j;
			ColorCell(cell,parseInt(LastWeekCorrectResults[i][j]));
		}					
	} 
}
/*Colors the 1 X 2 cells in the Main game table according to this week's results*/ 
function RefreshResultsDisplay(){
	var CorrectResults = correctResultsDisplayState();
	var cell;
	for (i=0;i<16;i++){
		for(j=0;j<3;j++){
			cell="cell"+i+j;
			ColorCell(cell,parseInt(CorrectResults[i][j]));
		}					
	} 
}

/*Colors the cell : cell_id, according to the color recieved:
   color: 1=Green(Correct guess), 2=Red(Wrong guess), 3=shaded Blue(Correct result, no guess), 0=Blue(Empty)*/
function ColorCell(cell_id,color){
	if (color==1) {
		document.getElementById(cell_id).setAttribute("class", "cellRight"); 
		return;
	}
	if (color==2) {
		document.getElementById(cell_id).setAttribute("class", "cellWrong");        
		return;
	}
	if (color==3) {
		document.getElementById(cell_id).setAttribute("class", "cellActuallGame");        
		return;
	}
	document.getElementById(cell_id).setAttribute("class", "cell");
}    

/*Updates the Team History information on its div, called from Team History button or when selecting past form to display*/
function getLastWeekInfo(appEngineCellUpperLimit) {
	
	//if we enter the 'if' it means we want to get the last week from the state, not from app engine
	if (appEngineCellUpperLimit==0){
	
	  document.getElementById("table_top_past_form").innerHTML= "שבוע שעבר : הטופס המלא ";
	   
		RefreshLastWeekGames(LastWeekGamesStrState()); //update the main table with the matches
		RefreshLastWeekStatistics(wave.getState().get( "lw_cost" ),wave.getState().get( "lw_prize" ),wave.getState().get( "lw_numberOfCorrectGuesses" )); //updates the cost,prize,num_of_correct_guesses
		RefreshLastWeekIdiot(wave.getState().get( "lw_idiotID" ),wave.getState().get( "lw_hotID" ));        //update the Idiot information (name&pic)
		RefreshLastWeekCells(lw_correctResultsDisplayState());     //update the table cells colors
	}
	else //when we enter the 'else' it means that we want to get the data from app engine
	{
	getOldForm(appEngineCellUpperLimit);	
	}
}
/*********	END OF TEAM HISTORY PART 	****************************/

/***** Page changes Functions *****/
function goToHelp(){
	document.getElementById('familyPage').style.display = 'none';
	document.getElementById('helpPage').style.display = 'block';	
} 
function backToGame(){
	document.getElementById('helpPage').style.display = 'none';
	document.getElementById('familyPage').style.display = 'block';	
}

/********** Button Action Functions ********************************/
function newGameMouseOver() {
	document.getElementById('new_game_left').style.backgroundPosition = "left -32px";
	document.getElementById('new_game_right').style.backgroundPosition = "right -32px";
}
function newGameMouseOut() {
	document.getElementById('new_game_left').style.backgroundPosition = "left 0px";
	document.getElementById('new_game_right').style.backgroundPosition = "right 0px";
}
function lastWeekMouseOver() {
	document.getElementById('last_week_left').style.backgroundPosition = "left -32px";
	document.getElementById('last_week_right').style.backgroundPosition = "right -32px";
}
function lastWeekMouseOut() {
	document.getElementById('last_week_left').style.backgroundPosition = "left 0px";
	document.getElementById('last_week_right').style.backgroundPosition = "right 0px";
}
function personalProfileMouseOver() {
	document.getElementById('personal_profile_left').style.backgroundPosition = "left -32px";
	document.getElementById('personal_profile_right').style.backgroundPosition = "right -32px";
}
function personalProfileMouseOut() {
	document.getElementById('personal_profile_left').style.backgroundPosition = "left 0px";
	document.getElementById('personal_profile_right').style.backgroundPosition = "right 0px";
}

var table = document.getElementById('content_table');

//this function gets x,y,z (amounts of clicks on 1,x,2) and displays a pie chart
function drawVisualization(x,y,z,game_num) {
	// Create and populate the data table.
	var data = new google.visualization.DataTable();
	data.addColumn('string', 'Task');
	data.addColumn('number', 'Hours per Day');
	data.addRows(3);
	data.setValue(0, 0, 'משחקים שסומנו ב-1');
	data.setValue(0, 1, x);
	data.setValue(1, 0, 'משחקים שסומנו בתיקו');
	data.setValue(1, 1, y);
	data.setValue(2, 0, 'משחקים שסומנו ב-2');
	data.setValue(2, 1, z);

	// Create and draw the visualization.
	//var chart=new google.visualization.PieChart(document.getElementById('div'));
	var chart=new google.visualization.ImagePieChart(document.getElementById('real_time_stat_div'));
	//var options={width: 400, height: 240, is3D: true,enableTooltip: true, title: 'Guesses Distribution'};
	var colorsArray=new Array('#0076BE','#82C025','#F2AC08');
	var options={width: 380, height: 200, labels:'value',is3D: true,legend:'bottom',colors:colorsArray,title: (game_num + 1) + " שאל את הקהל! משחק מספר "};
	chart.draw(data,options);
}

  /*This Function get an HTML div element and fill it with relevant match Statistics&Tips */
  function loadStat(el){
  	var el_id = el.id;
    var el_num = el_id.substr(4);
    var stats_links_arr= StatURLsState();

    document.getElementById("ifr_stat").src = stats_links_arr[15 - el_num];
    document.getElementById("tip_div").innerHTML = getRecByID(el_num);
  }
  /*This function updates the recieved div element with relevant tip*/
  function getRecByID(id){

     	var TempDiv="<h4> אין כרגע טיפ במערכת <br /> הטיפים מתפרסמים בכל יום רביעי בשעה 19:00 </h4> ";
			
      if(parseInt(wave.getState().get("RecommendationsReq"))){ //if a request for recommendations was made
				TextRecArr = Recommendations(1);
				FinalRecArr = Recommendations(0);	
				if((TextRecArr!="") && (FinalRecArr!="") && (TextRecArr[15-id]!=null) && (FinalRecArr[15-id]!=null)){
				  TempDiv="<h4> הטיפ שלנו: </h4> ";
					TempDiv +=  TextRecArr[15-id] + " ההימור שלנו: "+ FinalRecArr[15-id];
					}
				}
			
			return TempDiv;
		}
		
		/*This function adds 1 option to the select box of past forms*/
    function addItemToFormsTable(Text,Value,SelectElementID)
    {
        // Create an Option object        
        var opt = document.createElement("option");

        // Add an Option object to Drop Down/List Box
        document.getElementById(SelectElementID).options.add(opt);
        // Assign text and value to Option object
        opt.text = Text;
        opt.value = Value;
    }
    /* This function updates the form being viewed and it's relevant statistics on the team history(last week) page*/
    function updateLastWeekGame(){
      getLastWeekInfo(document.getElementById("pastForms_select").value);
    }
    
    /* This funcion updates the aggregated div info*/
    function updateLastWeekAggInfo(){
      var AggCost=getAggCost().toFixed(2);
	    if(AggCost && AggCost!=""){
		  document.getElementById( "form_cost_agg" ).innerHTML = AggCost;
    	}
	   var AggPrize= getAggPrize();
	   if(AggPrize && AggPrize!=""){
	   document.getElementById( "win_money_agg" ).innerHTML = AggPrize;    
	   }

	   //Update the aggregated idiot and hot picture and name
      var AggWeekIdiotID=wave.getState().get( "master_idiotID" );
      var AggWeekHotID=wave.getState().get( "master_hotID" );
    	
    	if(AggWeekIdiotID!="" && parseInt(AggWeekIdiotID)!=(-1)){
    		var AggWeekIdiot=wave.getParticipantById(AggWeekIdiotID); //get aggregated idiot wave participant obj
    		if (AggWeekIdiot && AggWeekIdiot!=""){
    			document.getElementById( "lw_idiot_img_agg" ).innerHTML ="<img src="+AggWeekIdiot.getThumbnailUrl()+" style='height:42px;width:42px'>";      
    			document.getElementById( "lw_idiot_name_agg" ).innerHTML = AggWeekIdiot.getDisplayName();
    		}
    	}
    	
    	if(AggWeekHotID!="" && parseInt(AggWeekHotID)!=(-1)){
    		var AggWeekHot=wave.getParticipantById(AggWeekHotID); //get aggregated hot wave participant obj
    		if (AggWeekHot && AggWeekHot!=""){
    			document.getElementById( "lw_king_img_agg" ).innerHTML ="<img src="+AggWeekHot.getThumbnailUrl()+" style='height:42px;width:42px'>";      
    			document.getElementById( "lw_king_name_agg" ).innerHTML = AggWeekHot.getDisplayName();
    		}
    	}
    	
    }
    
    /* This function updates the past forms select box with all the past forms*/  
    function createFormList(){
      if (select_box_updated==0){   //check that we didn't create the forms list yet
        var date;
    		var oldForms= getOldFormsListFromState();
      	for (i=0;i<oldForms.length;i++){
      		date=new Date(parseInt(oldForms[i]));
      		addItemToFormsTable(date.toLocaleDateString(),oldForms[i],"pastForms_select");
      	}
      	select_box_updated=1;
      }	
    }
    
    /*This function updates all the information on the Team history page*/
    function openTeamHistory(){
		if(wave.getState().get("lw_game")){	
			getLastWeekInfo(0);         //updates last week form and statistics
			updateLastWeekAggInfo();    //updates the aggrageted info
			createFormList();           //updates the past form list  
			document.getElementById( "no_last_week" ).setAttribute("style","display:none;");
			document.getElementById("lastweek_content").setAttribute("style","display:block;");
		}
		else{
			document.getElementById( "no_last_week" ).setAttribute("style","display:block;");
			document.getElementById("lastweek_content").setAttribute("style","display:none;");
		}
	}
	
    /*This function clears the real time statistics div when closing color box*/
    function clearChart(){
      document.getElementById( "real_time_stat_div" ).innerHTML = ""; 
    }
		
	/*This function builds the talkBack divs in the html*/
	function buildTBDivs(){
		/*var str="";
		for (var i=0;i<16;i++){
			str = str 	+ "<div id ='TB"+i+"' align = 'right' class='talkBack'>"		
						+ "<div id ='oldText"+i+"' dir='rtl' ></div>"	
						+ "<div id ='newTextDiv"+i+"'>"
						+ "<textarea id = 'newText"+i+"' rows='3' dir='rtl' style='margin-top: 10px;'></textarea>"
						+ "</div>"
						+"<div class='tb_button' onclick='submitTalkBack("+i+");'>"
						+"<div class='tb_button_left'>!הגב</div>"
						+"<div class='tb_button_right'>&nbsp;</div>"
						+"</div>"
						+"<div id ='TB2Agreement"+i+"' class='tb_button'>"
						+"<div class='tb_button_left'>עבור לטופס אישי</div>"
						+"<div class='tb_button_right'>&nbsp;</div>"
						+"</div>"
						+"</div>";
		}
		document.getElementById("TBDivs_frame").innerHTML = str;*/	
	}
		

